/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 错题接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const {
  ErrorQuestion,
  Question,
  Paper,
  User,
  ExamHistory,
  Exam
} = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, sortModel } = require('@/utils/controllerCommon')
const { uniqueArrayByKeyWithCount } = require('../utils')

/**
 * 列表查询错题接口
 * @param {*} ctx
 * @returns
 */
module.exports.listErrorQuestion = async (ctx) => {
  const { paperId, userId } = ctx.query
  const whereCondition = {
    userId: ctx.user.id
  }
  if (paperId !== undefined) {
    whereCondition.paperId = paperId
  }
  if (userId !== undefined) {
    whereCondition.userId = userId
  }
  const orderCondition = [['sort']]
  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await ErrorQuestion.findAndCountAll({
    where: whereCondition,
    include: [
      {
        model: Question
      },
      {
        model: Paper
      },
      {
        model: User
      }
    ],
    offset: +start,
    limit: +pageSize,
    order: orderCondition,
    distinct: true
  })

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

/**
 *  加载某个科目下错题试卷列表
 */
module.exports.listErrorPaper = async (ctx) => {
  const { examId } = ctx.query
  const whereCondition = { examId, userId: ctx.user.id }

  const orderCondition = [['sort']]
  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await ErrorQuestion.findAndCountAll({
    where: whereCondition,
    attributes: ['id', 'paperId', 'sort', 'examId'],
    include: [
      {
        model: Paper,
        include: [
          {
            model: ExamHistory
          }
        ]
      },
      {
        model: Exam
      }
    ],
    order: orderCondition,
    distinct: true
  })

  // 去重
  const finaRows = uniqueArrayByKeyWithCount(rows, 'paperId')

  ctx.body = R.success({
    page,
    pageSize,
    total: finaRows.length,
    pages: Math.ceil(count / pageSize),
    items: finaRows
  })
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 创建错题接口(一般为用户做答完毕后自动提交)
 * @param {*} ctx
 */
module.exports.createErrorQuestion = async (ctx) => {
  const { questionIds, paperId } = ctx.request.body
  const t = await Mysequelize.transaction()
  const sort = await ErrorQuestion.max('sort')
  const createArr = questionIds.map((item, index) => {
    const nextId = generatId()
    return {
      id: nextId,
      paperId,
      questionId: item,
      sort: sort + 1 + index,
      createUser: ctx.user.id,
      updateUser: ctx.user.id
    }
  })

  try {
    // 到这里可以进行错题的添加了,排序字段默认是最大值
    const errorQuestion = await ErrorQuestion.create(createArr, {
      transaction: t
    })
    await t.commit()
    ctx.body = R.success()
  } catch (error) {
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.ROLE_CREATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 更新错题接口
 * @param {*} ctx
 */
// module.exports.updateErrorQuestion = async (ctx) => {
//   const t = await Mysequelize.transaction()
//   const { errorQuestionId, name, desc, label, isVisible, permissionIds } =
//     ctx.request.body
//   const updateObj = {
//     name,
//     // type,
//     isVisible,
//     label
//   }
//   if (desc) {
//     updateObj.desc = desc
//   }

//   // 如果错题为系统预设，不进行权限的更新
//   const aErrorQuestion = await ErrorQuestion.findByPk(BigInt(errorQuestionId))
//   try {
//     // 进行错题信息的更新
//     await ErrorQuestion.update(updateObj, {
//       where: {
//         id: BigInt(errorQuestionId)
//       },
//       transaction: t
//     })
//     // 将此错题的权限全部删除后，重新设置
//     await ErrorQuestionPermission.destroy({
//       where: {
//         errorQuestionId: BigInt(errorQuestionId)
//       },
//       transaction: t
//     })

//     await updateErrorQuestionPermission(
//       permissionIds,
//       errorQuestionId,
//       ctx.user.id,
//       t
//     )
//     await t.commit()
//     ctx.body = R.success()
//   } catch (e) {
//     await t.rollback()
//     ctx.body = R.error(ERROR_USER_CODE.ROLE_UPDATE_ERROR)
//   }
// }

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除错题接口
 * @param {*} ctx
 */
module.exports.delErrorQuestions = async (ctx) => {
  await delModel(
    ErrorQuestion,
    ERROR_USER_CODE.ROLE_DEL_ERROR,
    'errorQuestionIds'
  )(ctx)
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 错题排序接口
 * @param {*} ctx
 */
module.exports.sortErrorQuestions = async (ctx) => {
  // 传递的错题ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    ErrorQuestion,
    ERROR_USER_CODE.ROLE_SORT_ERROR,
    'errorQuestionIds'
  )(ctx)
}
